package indi.mozping.aop;

import indi.mozping.dbutils.DBContextHolder;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author by mozping
 * @Classname DataSourceAop
 * @Description 自定义AOP，通过拦截来实现数据源的切换
 * 通过set选择的key来实现数据源的切换
 * @Date 2019/11/12 11:14
 */
@Aspect
@Component
public class DataSourceAop {
    /**
     * 从库的切点, 不包含Master注解，或者是方法名称包含find则走从库
     */
    @Pointcut("!@annotation(indi.mozping.annotation.Master) " +
            "&& (execution(* com.intellif.service..*.find*(..)))"
    )
    public void slavePointcut() {

    }

    /**
     * 主库的切点, 包含Master注解，或者是方法名称包含add/delete/update则走主库
     */
    @Pointcut("@annotation(indi.mozping.annotation.Master) " +
            "|| execution(* com.intellif.service..*.add*(..))" +
            "|| execution(* com.intellif.service..*.delete*(..))" +
            "|| execution(* com.intellif.service..*.update*(..))" +
            "|| execution(* com.intellif.service..*.realTimeFind*(..))"
    )
    public void masterPointcut() {
    }

    @Before("slavePointcut()")
    public void slave() {
        DBContextHolder.slave();
    }

    @Before("masterPointcut()")
    public void master() {
        DBContextHolder.master();
    }
}
